package com.itttq.kb.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.itttq.kb.model.po.TopicPo;
import com.itttq.kb.model.po.TopicReplyPo;
import com.itttq.kb.model.po.UserPo;
import com.itttq.kb.model.to.ResultTo;
import com.itttq.kb.service.TopicReplyService;

@RestController
@RequestMapping("topicReply")
public class TopicReplyController extends GenericController {
	private static final long serialVersionUID = -16383467055117467L;
	@Autowired
	private TopicReplyService topicReplyService;
	
	@RequestMapping("reply")
	public ModelAndView replyTopic(TopicReplyPo topicReply, Integer numberReply, HttpServletRequest request) {
		ModelAndView mv = new  ModelAndView("redirect:/topic/detail/"+topicReply.getTopicId() + ".html");
		ResultTo rt = new ResultTo(ResultTo.FAIL);
		if(topicReply != null) {
			// 从session获取user
			UserPo user = this.getUserBySession(request);
			if(null != user) {
				topicReply.setUpdaterId(user.getId()+0l);
				topicReply.setCreatorId(user.getId()+0l);
				topicReply.setCreatorName(user.getName());
				topicReply.setCreatorAvatar(user.getAvatar());
			}
			topicReplyService.addTopicReply(topicReply);
			try {
				// 更新回复数，此处有BUG，应该是+1的方式来做
				TopicPo tp = new TopicPo();
				tp.setId(topicReply.getTopicId().intValue());
				tp.setNumberReply((null == numberReply ? 0 : numberReply) + 1);
				topicService.updateTopic(tp);
			} catch (Exception e) {
				e.printStackTrace();
			}
			rt.setCode(ResultTo.SUCCESS);
		}
		return mv;
	}
}
